<?php

require_once ROOT_PATH . 'includes/fckeditor/fckeditor.php';
require_once ROOT_PATH . 'includes/cls_image.php';
require_once ROOT_PATH . 'admin/models/ServiceAddressModel.php';

/* 初始化数据交换对象 */
$exc = new exchange($ecs->table("service_address"), $db, 'article_id', 'title');
/* 允许上传的文件类型 */
$allow_file_types = '|GIF|JPG|PNG|BMP|SWF|DOC|XLS|PPT|MID|WAV|ZIP|RAR|PDF|CHM|RM|TXT|';

class ServiceAddressController {

  public function __construct() {
    $this->addressModel = new ServiceAddressModel();
  }

  public function showList() {
    $filter = array();
    $GLOBALS['smarty']->assign('cat_select', $this->addressModel->article_cat_list(0));
    $GLOBALS['smarty']->assign('ur_here', '网点列表');
    $GLOBALS['smarty']->assign('action_link', array('text' => '增加网点', 'href' => 'service_address.php?act=add'));
    $GLOBALS['smarty']->assign('full_page', 1);
    $GLOBALS['smarty']->assign('filter', $filter);

    $article_list = $this->addressModel->get_articleslist();

    $GLOBALS['smarty']->assign('article_list', $article_list['arr']);
    $GLOBALS['smarty']->assign('filter', $article_list['filter']);
    $GLOBALS['smarty']->assign('record_count', $article_list['record_count']);
    $GLOBALS['smarty']->assign('page_count', $article_list['page_count']);

    $sort_flag = sort_flag($article_list['filter']);
    $GLOBALS['smarty']->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    $GLOBALS['smarty']->display('service/service_address_list.htm');
  }

  public function query() {
    check_authz_json('article_manage');

    $article_list = $this->addressModel->get_articleslist();

    $GLOBALS['smarty']->assign('article_list', $article_list['arr']);
    $GLOBALS['smarty']->assign('filter', $article_list['filter']);
    $GLOBALS['smarty']->assign('record_count', $article_list['record_count']);
    $GLOBALS['smarty']->assign('page_count', $article_list['page_count']);

    $sort_flag = sort_flag($article_list['filter']);
    $GLOBALS['smarty']->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($GLOBALS['smarty']->fetch('service/service_address_list.htm'), '', array('filter' => $article_list['filter'], 'page_count' => $article_list['page_count']));
  }

  public function add() {
    /* 权限判断 */
    admin_priv('article_manage');

    /* 创建 html editor */
    create_html_editor('FCKeditor1');

    /* 初始化 */
    $article = array();
    $article['is_open'] = 1;


    if (isset($_GET['id'])) {
      $GLOBALS['smarty']->assign('cur_id', $_GET['id']);
    }
    $GLOBALS['smarty']->assign('article', $article);
    $GLOBALS['smarty']->assign('cat_select', $this->addressModel->article_cat_list(0));
    $GLOBALS['smarty']->assign('ur_here', '增加网点');
    $GLOBALS['smarty']->assign('action_link', array('text' => '网点列表', 'href' => 'service_address.php?act=list'));
    $GLOBALS['smarty']->assign('form_action', 'insert');

    assign_query_info();
    $GLOBALS['smarty']->display('service/service_info.htm');
  }

  public function insert() {
    /* 权限判断 */
    admin_priv('article_manage');

    /* 检查是否重复 */
    $is_only = $GLOBALS['exc']->is_only('title', $_POST['title'], 0, " cat_id ='$_POST[article_cat]'");

    if (!$is_only) {
      sys_msg(sprintf($GLOBALS['_LANG']['title_exist'], stripslashes($_POST['title'])), 1);
    }

    /* 取得文件地址 */
    $file_url = '';
    if ((isset($_FILES['file']['error']) && $_FILES['file']['error'] == 0) || (!isset($_FILES['file']['error']) && isset($_FILES['file']['tmp_name']) && $_FILES['file']['tmp_name'] != 'none')) {
      // 检查文件格式
      if (!check_file_type($_FILES['file']['tmp_name'], $_FILES['file']['name'], $GLOBALS['allow_file_types'])) {
        sys_msg($GLOBALS['_LANG']['invalid_file']);
      }

      // 复制文件
      $res = $this->addressModel->upload_article_file($_FILES['file']);
      if ($res != false) {
        $file_url = $res;
      }
    }

    if ($file_url == '') {
      $file_url = $_POST['file_url'];
    }

    /* 计算文章打开方式 */
    if ($file_url == '') {
      $open_type = 0;
    } else {
      $open_type = $_POST['FCKeditor1'] == '' ? 1 : 2;
    }

    /* 插入数据 */
    $add_time = gmtime();
    if (empty($_POST['cat_id'])) {
      $_POST['cat_id'] = 0;
    }
    $sql = "INSERT INTO " . $GLOBALS['ecs']->table('service_address') . "(title, cat_id, is_open, " .
            "content, add_time, file_url, open_type, link, description) " .
            "VALUES ('$_POST[title]', '$_POST[article_cat]', '$_POST[is_open]', " .
            "'$_POST[FCKeditor1]', " .
            "'$add_time', '$file_url', '$open_type', '$_POST[link_url]', '$_POST[description]')";
    $GLOBALS['db']->query($sql);

    $link[0]['text'] = '继续添加网点';
    $link[0]['href'] = 'service_address.php?act=add';

    $link[1]['text'] = '返回网点列表';
    $link[1]['href'] = 'service_address.php?act=list';

    admin_log($_POST['title'], 'add', 'service_address');

    clear_cache_files(); // 清除相关的缓存文件

    sys_msg('成功添加网点', 0, $link);
  }

  public function remove() {
    check_authz_json('article_manage');

    $id = intval($_GET['id']);

    /* 删除原来的文件 */
    $sql = "SELECT file_url FROM " . $GLOBALS['ecs']->table('service_address') . " WHERE article_id = '$id'";
    $old_url = $GLOBALS['db']->getOne($sql);
    if ($old_url != '' && strpos($old_url, 'http://') === false && strpos($old_url, 'https://') === false) {
      @unlink(ROOT_PATH . $old_url);
    }

    $name = $GLOBALS['exc']->get_name($id);
    if ($GLOBALS['exc']->drop($id)) {
      clear_cache_files();
    }

    $url = 'service_address.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
  }

  public function edit() {
    /* 权限判断 */
    admin_priv('article_manage');

    /* 取文章数据 */
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('service_address') . " WHERE article_id='$_REQUEST[id]'";
    $article = $GLOBALS['db']->GetRow($sql);

    /* 创建 html editor */
    create_html_editor('FCKeditor1', $article['content']);

    $GLOBALS['smarty']->assign('article', $article);
    $GLOBALS['smarty']->assign('cat_select', $this->addressModel->article_cat_list(0, $article['cat_id']));
    $GLOBALS['smarty']->assign('ur_here', '编辑网点');
    $GLOBALS['smarty']->assign('action_link', array('text' => '网点列表', 'href' => 'service_address.php?act=list&' . list_link_postfix()));
    $GLOBALS['smarty']->assign('form_action', 'update');

    assign_query_info();
    $GLOBALS['smarty']->display('service/service_info.htm');
  }

  public function update() {
    /* 权限判断 */
    admin_priv('article_manage');

    /* 检查文章名是否相同 */
    $is_only = $GLOBALS['exc']->is_only('title', $_POST['title'], $_POST['id'], "cat_id = '$_POST[article_cat]'");

    if (!$is_only) {
      sys_msg(sprintf($GLOBALS['_LANG']['title_exist'], stripslashes($_POST['title'])), 1);
    }


    if (empty($_POST['cat_id'])) {
      $_POST['cat_id'] = 0;
    }

    /* 取得文件地址 */
    $file_url = '';
    if (empty($_FILES['file']['error']) || (!isset($_FILES['file']['error']) && isset($_FILES['file']['tmp_name']) && $_FILES['file']['tmp_name'] != 'none')) {
      // 检查文件格式
      if (!check_file_type($_FILES['file']['tmp_name'], $_FILES['file']['name'], $GLOBALS['allow_file_types'])) {
        sys_msg($GLOBALS['_LANG']['invalid_file']);
      }

      // 复制文件
      $res = $this->addressModel->upload_article_file($_FILES['file']);
      if ($res != false) {
        $file_url = $res;
      }
    }

    if ($file_url == '') {
      $file_url = $_POST['file_url'];
    }

    /* 计算文章打开方式 */
    if ($file_url == '') {
      $open_type = 0;
    } else {
      $open_type = $_POST['FCKeditor1'] == '' ? 1 : 2;
    }

    /* 如果 file_url 跟以前不一样，且原来的文件是本地文件，删除原来的文件 */
    $sql = "SELECT file_url FROM " . $GLOBALS['ecs']->table('service_address') . " WHERE article_id = '$_POST[id]'";
    $old_url = $GLOBALS['db']->getOne($sql);
    if ($old_url != '' && $old_url != $file_url && strpos($old_url, 'http://') === false && strpos($old_url, 'https://') === false) {
      @unlink(ROOT_PATH . $old_url);
    }

    if ($GLOBALS['exc']->edit("title='$_POST[title]', cat_id='$_POST[article_cat]', article_type='$_POST[article_type]', is_open='$_POST[is_open]', author='$_POST[author]', author_email='$_POST[author_email]', keywords ='$_POST[keywords]', file_url ='$file_url', open_type='$open_type', content='$_POST[FCKeditor1]', link='$_POST[link_url]', description = '$_POST[description]'", $_POST['id'])) {
      $link[0]['text'] = $GLOBALS['_LANG']['back_list'];
      $link[0]['href'] = 'service_address.php?act=list&' . list_link_postfix();

      $note = sprintf($$GLOBALS['_LANG']['articleedit_succeed'], stripslashes($_POST['title']));
      admin_log($_POST['title'], 'edit', 'service_address');

      clear_cache_files();

      sys_msg($note, 0, $link);
    } else {
      die($GLOBALS['db']->error());
    }
  }
  
  public function batch() {
    /* 批量删除 */
    if (isset($_POST['type'])) {
      if ($_POST['type'] == 'button_remove') {
        admin_priv('article_manage');

        if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes'])) {
          sys_msg($GLOBALS['_LANG']['no_select_article'], 1);
        }

        /* 删除原来的文件 */
        $sql = "SELECT file_url FROM " . $GLOBALS['ecs']->table('service_address') .
                " WHERE article_id " . db_create_in(join(',', $_POST['checkboxes'])) .
                " AND file_url <> ''";

        $res = $GLOBALS['db']->query($sql);
        while ($row = $GLOBALS['db']->fetchRow($res)) {
          $old_url = $row['file_url'];
          if (strpos($old_url, 'http://') === false && strpos($old_url, 'https://') === false) {
            @unlink(ROOT_PATH . $old_url);
          }
        }

        foreach ($_POST['checkboxes'] AS $key => $id) {
          if ($GLOBALS['exc']->drop($id)) {
            $name = $GLOBALS['exc']->get_name($id);
            admin_log(addslashes($name), 'remove', 'article');
          }
        }
      }

      /* 批量隐藏 */
      if ($_POST['type'] == 'button_hide') {
        check_authz_json('article_manage');
        if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes'])) {
          sys_msg($GLOBALS['_LANG']['no_select_article'], 1);
        }

        foreach ($_POST['checkboxes'] AS $key => $id) {
          $GLOBALS['exc']->edit("is_open = '0'", $id);
        }
      }

      /* 批量显示 */
      if ($_POST['type'] == 'button_show') {
        check_authz_json('article_manage');
        if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes'])) {
          sys_msg($GLOBALS['_LANG']['no_select_article'], 1);
        }

        foreach ($_POST['checkboxes'] AS $key => $id) {
          $GLOBALS['exc']->edit("is_open = '1'", $id);
        }
      }

      /* 批量移动分类 */
      if ($_POST['type'] == 'move_to') {
        check_authz_json('article_manage');
        if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes'])) {
          sys_msg($GLOBALS['_LANG']['no_select_article'], 1);
        }

        if (!$_POST['target_cat']) {
          sys_msg($GLOBALS['_LANG']['no_select_act'], 1);
        }

        foreach ($_POST['checkboxes'] AS $key => $id) {
          $GLOBALS['exc']->edit("cat_id = '" . $_POST['target_cat'] . "'", $id);
        }
      }
    }

    /* 清除缓存 */
    clear_cache_files();
    $lnk[] = array('text' => $GLOBALS['_LANG']['back_list'], 'href' => 'service_address.php?act=list');
    sys_msg($GLOBALS['_LANG']['batch_handle_ok'], 0, $lnk);
  }

}